import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { QRCodeSVG } from "qrcode.react";
import { z } from "zod";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import html2canvas from 'html2canvas';

// WiFi QR Code format: WIFI:S:<SSID>;T:<TYPE>;P:<PASSWORD>;H:<HIDDEN>;;
// TYPE can be WPA, WEP, or nopass
// HIDDEN is true or false

const wifiSchema = z.object({
  ssid: z.string().min(1, "WiFi名称不能为空"),
  password: z.string().min(1, "密码不能为空"),
  security: z.enum(["WPA", "WPA2", "WPA3", "WEP", "nopass"]),
  hidden: z.boolean().optional().default(false),
  title: z.string().optional(),
  encrypt: z.boolean().optional().default(false),
  encryptionKey: z.string().optional(),
});

type WiFiFormData = z.infer<typeof wifiSchema>;

// 简单的XOR加密函数
const xorEncrypt = (text: string, key: string): string => {
  let result = "";
  for (let i = 0; i < text.length; i++) {
    const textCharCode = text.charCodeAt(i);
    const keyCharCode = key.charCodeAt(i % key.length);
    result += String.fromCharCode(textCharCode ^ keyCharCode);
  }
  return btoa(result); // 转换为Base64以便安全显示
};

// 简单的XOR解密函数
const xorDecrypt = (encryptedText: string, key: string): string => {
  const decodedText = atob(encryptedText);
  let result = "";
  for (let i = 0; i < decodedText.length; i++) {
    const textCharCode = decodedText.charCodeAt(i);
    const keyCharCode = key.charCodeAt(i % key.length);
    result += String.fromCharCode(textCharCode ^ keyCharCode);
  }
  return result;
};

export default function WiFiQRCodeGenerator() {
  const navigate = useNavigate();
  const [formData, setFormData] = useState<WiFiFormData>({
    ssid: "",
    password: "",
    security: "WPA",
    hidden: false,
    title: "",
  });
  const [isGenerating, setIsGenerating] = useState(false);
  const [qrCodeValue, setQrCodeValue] = useState("");
  const [errors, setErrors] = useState<Partial<Record<keyof WiFiFormData, string>>>({});
  // 背景自定义状态
  const [backgroundType, setBackgroundType] = useState<'solid' | 'image'>('solid');
  const [backgroundColor, setBackgroundColor] = useState('#ffffff');
  const [backgroundImage, setBackgroundImage] = useState<string | null>(null);

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  // 处理背景图片上传
  const handleBackgroundImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        setBackgroundImage(event.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  // 清除背景图片
  const clearBackgroundImage = () => {
    setBackgroundImage(null);
    const fileInput = document.getElementById('background-image-upload') as HTMLInputElement;
    if (fileInput) fileInput.value = '';
  };

  const validateForm = (): boolean => {
    const result = wifiSchema.safeParse(formData);
    if (!result.success) {
      const newErrors: Partial<Record<keyof WiFiFormData, string>> = {};
      result.error.issues.forEach((issue) => {
        const field = issue.path[0] as keyof WiFiFormData;
        newErrors[field] = issue.message;
      });
      setErrors(newErrors);
      return false;
    }
    setErrors({});
    return true;
  };

  const generateQRCode = () => {
    if (!validateForm()) return;

    setIsGenerating(true);
    
    // Format WiFi QR code according to the standard
     // 生成标准WiFi QR码格式，移动设备扫描可直接连接且不显示密码
     const wifiString = `WIFI:S:${formData.ssid};T:${formData.security};P:${formData.password};H:${formData.hidden ? "true" : "false"};;`;
    
    setQrCodeValue(wifiString);
    
    setTimeout(() => {
      setIsGenerating(false);
      toast.success("WiFi二维码生成成功！");
    }, 800);
  };

  const downloadQRCode = () => {
    if (!qrCodeValue) return;
    
    // 选择要下载的整个内容区域
       // 选择只包含二维码标题和二维码的容器
       const content = document.querySelector('.qr-code-printable-content');
    if (!content) return;
    
    // 使用html2canvas捕获内容
    html2canvas(content, {
      scale: 2, // 提高分辨率
      useCORS: true,
      logging: false
    }).then(canvas => {
      const link = document.createElement("a");
      // 使用标题作为文件名（如果有）
      const fileName = formData.title 
        ? `${formData.title.replace(/\s+/g, '_')}_WiFi_QRCode.png` 
        : `WiFi_${formData.ssid}_QRCode.png`;
      link.download = fileName;
      link.href = canvas.toDataURL("image/png");
      link.click();
      
      toast.success("整页内容下载成功！");
    }).catch(err => {
      console.error("下载失败:", err);
      toast.error("下载失败，请重试");
    });
  };

   const copyToClipboard = () => {
    if (!qrCodeValue) return;
    
    // 使用XOR加密算法加密WiFi信息
    const encryptionKey = 'wifi-qr-encrypt-key'; // 可以考虑让用户自定义密钥
    const encryptedValue = xorEncrypt(qrCodeValue, encryptionKey);
    
    navigator.clipboard.writeText(encryptedValue).then(() => {
      toast.success("加密后的WiFi连接信息已复制到剪贴板");
    }).catch(() => {
      toast.error("复制失败，请手动复制");
    });
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-4">
      <div className="max-w-4xl mx-auto">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold text-gray-800 dark:text-white">WiFi二维码生成器</h1>
          <button
            onClick={() => navigate("/")}
            className="text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors"
          >
            <i className="fa-solid fa-arrow-left mr-1"></i> 返回首页
          </button>
        </div>
        
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg overflow-hidden qr-code-content-container">
           <div className="grid md:grid-cols-2 gap-8">
             {/* Form Section */}
             <div className="p-8 form-section">
               <h2 className="text-xl font-semibold text-gray-700 dark:text-gray-200 mb-6">WiFi信息设置</h2>
               
                <div className="space-y-5">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      二维码标题
                    </label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i className="fa-solid fa-tag text-gray-400"></i>
                      </div>
                      <input
                        type="text"
                        name="title"
                        value={formData.title}
                        onChange={handleInputChange}
                        className={`w-full pl-10 pr-4 py-3 rounded-lg border ${
                          errors.title
                            ? "border-red-500 focus:ring-red-500"
                            : "border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400"
                        } focus:ring-2 focus:outline-none transition-colors dark:bg-gray-700 dark:text-white`}
                        placeholder="输入二维码标题（可选）"
                      />
                    </div>
                    {errors.title && (
                      <p className="mt-1 text-sm text-red-500">{errors.title}</p>
                    )}
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      WiFi名称 (SSID)
                    </label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i className="fa-solid fa-wifi text-gray-400"></i>
                      </div>
                      <input
                        type="text"
                        name="ssid"
                        value={formData.ssid}
                        onChange={handleInputChange}
                        className={`w-full pl-10 pr-4 py-3 rounded-lg border ${
                          errors.ssid
                            ? "border-red-500 focus:ring-red-500"
                            : "border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400"
                        } focus:ring-2 focus:outline-none transition-colors dark:bg-gray-700 dark:text-white`}
                        placeholder="输入WiFi名称"
                      />
                    </div>
                    {errors.ssid && (
                      <p className="mt-1 text-sm text-red-500">{errors.ssid}</p>
                    )}
                  </div>
                 
                 <div>
                   <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                     WiFi密码
                   </label>
                   <div className="relative">
                     <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                       <i className="fa-solid fa-lock text-gray-400"></i>
                     </div>
                     <input
                       type="password"
                       name="password"
                       value={formData.password}
                       onChange={handleInputChange}
                       className={`w-full pl-10 pr-4 py-3 rounded-lg border ${
                         errors.password
                           ? "border-red-500 focus:ring-red-500"
                           : "border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400"
                       } focus:ring-2 focus:outline-none transition-colors dark:bg-gray-700 dark:text-white`}
                       placeholder="输入WiFi密码"
                     />
                   </div>
                   {errors.password && (
                     <p className="mt-1 text-sm text-red-500">{errors.password}</p>
                   )}
                 </div>
                 
                 <div className="grid grid-cols-2 gap-4">
                   <div>
                     <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                       安全类型
                     </label>
                      <select
                        name="security"
                        value={formData.security}
                        onChange={handleInputChange}
                        className="w-full pl-4 pr-10 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:outline-none transition-colors dark:bg-gray-700 dark:text-white"
                      >
                        <option value="WPA">WPA/WPA2</option>
                        <option value="WPA2">WPA2</option>
                        <option value="WPA3">WPA3</option>
                        <option value="WEP">WEP</option>
                        <option value="nopass">无密码</option>
                      </select>
                   </div>
                   
                    <div className="flex items-end">
                      <div className="flex items-center">
                        <input
                          type="checkbox"
                          name="hidden"
                          id="hidden"
                          checked={formData.hidden}
                          onChange={handleInputChange}
                          className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600"
                        />
                        <label
                          htmlFor="hidden"
                          className="ml-2 block text-sm text-gray-700 dark:text-gray-300"
                        >
                          隐藏网络
                        </label>
                   </div>
                 </div>

                 {/* 背景自定义设置 */}
                 <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                   <h3 className="text-lg font-medium text-gray-800 dark:text-white mb-4">二维码背景设置</h3>
                   
                   <div className="mb-4">
                     <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                       背景类型
                     </label>
                     <div className="flex space-x-4">
                       <label className="inline-flex items-center">
                         <input
                           type="radio"
                           name="backgroundType"
                           value="solid"
                           checked={backgroundType === 'solid'}
                           onChange={() => setBackgroundType('solid')}
                           className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600"
                         />
                         <span className="ml-2 text-sm text-gray-700 dark:text-gray-300">纯色背景</span>
                       </label>
                       <label className="inline-flex items-center">
                         <input
                           type="radio"
                           name="backgroundType"
                           value="image"
                           checked={backgroundType === 'image'}
                           onChange={() => setBackgroundType('image')}
                           className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded dark:bg-gray-700 dark:border-gray-600"
                         />
                         <span className="ml-2 text-sm text-gray-700 dark:text-gray-300">图片背景</span>
                       </label>
                     </div>
                   </div>
                   
                   {backgroundType === 'solid' && (
                     <div className="mb-4">
                       <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                         背景颜色
                       </label>
                       <div className="flex items-center space-x-3">
                         <input
                           type="color"
                           value={backgroundColor}
                           onChange={(e) => setBackgroundColor(e.target.value)}
                           className="h-10 w-10 p-0 border border-gray-300 rounded dark:border-gray-600"
                         />
                         <input
                           type="text"
                           value={backgroundColor}
                           onChange={(e) => setBackgroundColor(e.target.value)}
                           className="flex-1 pl-4 pr-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:outline-none transition-colors dark:bg-gray-700 dark:text-white"
                           placeholder="输入颜色代码"
                         />
                       </div>
                     </div>
                   )}
                   
                   {backgroundType === 'image' && (
                     <div className="mb-4">
                       <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                         背景图片
                       </label>
                       <div className="flex flex-col space-y-3">
                         <input
                           id="background-image-upload"
                           type="file"
                           accept="image/*"
                           onChange={handleBackgroundImageUpload}
                           className="pl-4 pr-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:outline-none transition-colors dark:bg-gray-700 dark:text-white"
                         />
                         
                         {backgroundImage ? (
                           <div className="relative bg-gray-100 dark:bg-gray-700 rounded-lg p-2 flex items-center">
                             <img 
                               src={backgroundImage} 
                               alt="Background preview" 
                               className="h-24 object-cover rounded"
                             />
                             <button
                               onClick={clearBackgroundImage}
                               className="ml-3 text-red-500 hover:text-red-700 transition-colors"
                             >
                               <i className="fa-solid fa-times-circle"></i> 移除图片
                             </button>
                           </div>
                         ) : (
                           <p className="text-xs text-gray-500 dark:text-gray-400">
                             支持JPG、PNG格式图片，建议使用浅色或简洁图案，避免影响二维码识别
                           </p>
                         )}
                       </div>
                     </div>
                   )}
                 </div>
                  </div>
                  
                   <div className="pt-2 bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg text-sm">
                     <div className="flex items-start gap-2">
                       <i className="fa-solid fa-shield text-blue-500 mt-0.5"></i>
                       <div>
                         <p className="font-medium text-gray-800 dark:text-white">安全提示</p>
                         <p className="text-gray-600 dark:text-gray-300 mt-1">使用手机相机扫描可直接连接WiFi，不会显示密码。通用QR码扫描器可能显示网络名称，但密码受保护。</p>
                       </div>
                     </div>
                   </div>
                 
                 <div className="pt-2">
                   <button
                     onClick={generateQRCode}
                     disabled={isGenerating}
                     className={`w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 ${
                       isGenerating ? "opacity-70 cursor-not-allowed" : "hover:shadow-lg"
                     } flex items-center justify-center gap-2`}
                   >
                     {isGenerating ? (
                       <>
                         <i className="fa-solid fa-spinner fa-spin"></i>
                         生成中...
                       </>
                     ) : (
                       <>
                         <i className="fa-solid fa-magic"></i>
                         生成二维码
                       </>
                     )}
                   </button>
                 </div>
               </div>
             </div>
             
             {/* QR Code Preview Section */}
             <div className="bg-gray-50 dark:bg-gray-900 p-8 flex flex-col items-center justify-center">
               <div className="qr-print-download-container w-full max-w-xs">
                 <h2 className="text-xl font-semibold text-gray-700 dark:text-gray-200 mb-6 text-center">二维码预览</h2>
               
                 {qrCodeValue ? (
                    <div 
                      className="qr-code-printable-content p-6 rounded-xl shadow-md mb-6 transform transition-all duration-500 hover:shadow-xl"
                      style={{
                        backgroundColor: backgroundColor,
                        backgroundImage: backgroundImage ? `url(${backgroundImage})` : 'none',
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                        backgroundRepeat: 'no-repeat'
                      }}
                    >
                      <div className="text-center mb-4">
                        <h3 className="text-lg font-semibold text-gray-800 dark:text-white">
                          {formData.title ? `${formData.title} - ${formData.ssid}` : formData.ssid}
                        </h3>
                        <p className="text-sm text-gray-600 dark:text-gray-400">请扫码连接</p>
                      </div>
                     <div className="flex justify-center">
                       <QRCodeSVG
                         value={qrCodeValue}
                         size={200}
                         level="M"
                         className="transition-opacity duration-300"
                       />
                     </div>
                      <div className="mt-4 text-center text-xs text-gray-500 dark:text-gray-400 p-2 rounded">
                       <i className="fa-solid fa-wifi mr-1"></i>
                       使用手机相机扫描即可快速连接WiFi，无需输入密码
                     </div>
                   </div>
                 ) : (
                   <div className="bg-white dark:bg-gray-800 p-12 rounded-xl shadow-md mb-6 flex flex-col items-center justify-center h-64">
                     <div className="text-gray-400 text-center">
                       <i className="fa-solid fa-qrcode text-6xl mb-4 opacity-30"></i>
                       <p>填写WiFi信息并点击"生成二维码"</p>
                     </div>
                   </div>
                 )}
                 
                 {qrCodeValue && (
                    <div className="grid grid-cols-3 gap-4 qr-actions">
                     <button
                       onClick={downloadQRCode}
                       className="bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center justify-center gap-2"
                     >
                       <i className="fa-solid fa-download"></i>
                       下载
                     </button>
                     <button
                       onClick={copyToClipboard}
                       className="bg-purple-600 hover:bg-purple-700 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center justify-center gap-2"
                     >
                       <i className="fa-solid fa-copy"></i>
                       复制信息
                     </button>
                     <button
                       onClick={() => window.print()}
                       className="bg-orange-600 hover:bg-orange-700 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center justify-center gap-2"
                     >
                       <i className="fa-solid fa-print"></i>
                       打印
                     </button>
                   </div>
                 )}
                 
                  {qrCodeValue && (
                    <div className="mt-6 p-4 bg-gray-100 dark:bg-gray-800 rounded-lg text-sm qr-info-preview">
                     <p className="text-gray-500 dark:text-gray-400 mb-1 font-medium">WiFi信息预览:</p>
                     <p className="text-gray-700 dark:text-gray-300 truncate">{formData.ssid}</p>
                     <p className="text-gray-600 dark:text-gray-400 text-xs mt-1">
                        安全类型: {formData.security === "WPA" ? "WPA/WPA2" : formData.security === "WPA2" ? "WPA2" : formData.security === "WPA3" ? "WPA3" : formData.security === "WEP" ? "WEP" : "无密码"}
                       {formData.hidden && ", 隐藏网络"}
                     </p>
                   </div>
                 )}
                 
                 {/* 使用说明 - 移到二维码容器内以便下载和打印 */}
                  {qrCodeValue && (
                    <div className="mt-6 bg-white dark:bg-gray-800 rounded-xl shadow p-4">
                      <h3 className="text-base font-semibold text-gray-800 dark:text-white mb-2">使用说明</h3>
                      <ul className="text-gray-600 dark:text-gray-300 text-sm space-y-1.5">
                        <li className="flex items-start gap-2">
                          <i className="fa-solid fa-mobile-screen-button text-blue-500 mt-0.5 flex-shrink-0"></i>
                          <span>使用手机相机扫描二维码，无需安装额外应用</span>
                        </li>
                        <li className="flex items-start gap-2">
                          <i className="fa-solid fa-wifi text-green-500 mt-0.5 flex-shrink-0"></i>
                          <span>扫描后将自动连接WiFi，无需手动输入密码</span>
                        </li>
                        <li className="flex items-start gap-2">
                          <i className="fa-solid fa-lock text-purple-500 mt-0.5 flex-shrink-0"></i>
                          <span>密码将被安全加密处理，不会在扫描界面显示</span>
                        </li>
                        <li className="flex items-start gap-2">
                          <i className="fa-solid fa-print text-orange-500 mt-0.5 flex-shrink-0"></i>
                          <span>建议下载并打印此二维码，放置在显眼位置供客人使用</span>
                        </li>
                      </ul>
                    </div>
                  )}
               </div>
             </div>
           </div>
         </div>
      </div>
    </div>
  );
}